<template>
  <a-modal :width="1300" v-model:visible="showEditDialog" title="生产计划" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <div class="flex-c" style="margin-bottom: 10px">
      <span>生产入库仓：</span>
      <a-select v-model="warehouseInfo" value-key="warehouseCode" allow-search placeholder="" style="width: 240px">
        <a-option v-for="(item, i) in useBaseData.warehouseList" :key="i" :value="item" :label="item.warehouseName" />
      </a-select>
    </div>
    <a-table
      class="table-normal-line s"
      ref="tableRef"
      row-key="key"
      :data="purchaseOrders"
      :scroll="{
        y: 'calc(84vh - 200px)',
      }"
      size="mini"
      :bordered="false"
      :pagination="false"
    >
      <template #columns>
        <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
          <template #title v-if="item.tip">
            <a-popover>
              <template #content>
                <p v-for="(str, i) in item.tip.split('--')" :key="i" style="max-width: 500px">{{ str }}</p>
              </template>
              <p>
                <span>{{ item.title }}</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #title v-else-if="item.dataIndex == 'productionProcedureId'">
            <div class="flex-c">
              <span>生产工序</span>
              <icon-plus-circle class="highlight cursor add-procedure" @click="showProductionProcedure = true" />
            </div>
          </template>
          <template #cell="{ record, rowIndex }">
            <!-- 采购单号 -->
            <p v-if="item.dataIndex == 'purchaseNo'" class="highlight">{{ record.purchaseNo }}</p>
            <!-- 产品 -->
            <div v-else-if="item.dataIndex == 'sku'" class="flex-c">
              <ImgPopover :src="record.productImg">
                <template #con>
                  <a-image width="50" height="50" fit="contain" :src="record.productImg" />
                </template>
              </ImgPopover>
              <a-popover position="bottom">
                <template #content>
                  <div style="max-width: 400px">
                    <p>品名：{{ record.productName }}</p>
                    <p>SKU：{{ record.sku }}</p>
                    <p>SPU：{{ record.spu }}</p>
                    <p>类目：{{ record.cateName }}</p>
                    <p style="margin-bottom: 20px">规格：{{ getProductSpecs(record) }}</p>
                    <p v-for="(prop, k) in record.purchaseSpecsArr" :key="k">
                      <span>{{ prop.name }}：</span>
                      <span>{{ getStrVal(prop.purchaseValue) }}</span>
                    </p>
                  </div>
                </template>
                <div style="margin-left: 5px; flex: 1">
                  <p class="highlight">{{ record.sku }}</p>
                  <TextLimit :val="getProductSpecs(record)" :rows="1" />
                </div>
              </a-popover>
            </div>
            <!-- 生产参数 -->
            <template v-else-if="item.dataIndex == 'prop'">
              <PurchasePropPopover v-if="record.purchaseSpecsArr" :purchaseSpecsArr="record.purchaseSpecsArr" />
            </template>
            <!-- 材质 -->
            <p v-else-if="item.dataIndex == 'material'">{{ getMaterial(record) }}</p>
            <!-- 类型 -->
            <p v-else-if="item.dataIndex == 'productType'">{{ productTypeMap[record.productType] || record.productType }}</p>
            <!-- 需生产数量 -->
            <div v-else-if="item.dataIndex == 'num'" class="cell flex-c" style="width: 80px">
              <a-input-number :precision="0" :min="0" v-model="record.num" style="width: 60px" placeholder="" hide-button />
              <icon-double-down v-if="rowIndex < purchaseOrders.length - 1" class="edit-icon" @click="setGlobal(record, 'num', rowIndex)" />
            </div>
            <!-- 生产工序 -->
            <div v-else-if="item.dataIndex == 'productionProcedureId'" class="cell flex-c" style="width: 130px">
              <a-select size="medium" v-model="record.productionProcedureId" allow-search placeholder="" style="width: 110px">
                <a-option v-for="(el, i) in productionProcedure" :key="i" :value="el.id" :label="el.templateName" />
              </a-select>
              <icon-double-down v-if="rowIndex < purchaseOrders.length - 1" class="edit-icon" @click="setGlobal(record, 'productionProcedureId', rowIndex)" />
            </div>
            <!-- 配件 -->
            <div v-else-if="item.dataIndex == 'partsList'" class="cell flex-c">
              <a-popover position="bottom" v-if="record.partsList && record.partsList.length">
                <template #content>
                  <a-table class="table-normal-line show-border-table" :scroll="{ x: 400, y: 300 }" :data="record.partsList" size="mini" :pagination="false">
                    <template #columns>
                      <a-table-column data-index="partsName" title="配件" />
                      <a-table-column data-index="partsSpecs" title="规格&尺寸" />
                      <a-table-column data-index="partsAmt" title="数量" />
                      <a-table-column data-index="partsWeight" title="重量（g）" />
                    </template>
                  </a-table>
                </template>
                <div style="margin-left: 5px; flex: 1">
                  <p class="text-limit-two">{{ record.partsList.map((el: any) => el.partsName).join(',') }}</p>
                </div>
              </a-popover>
              <p>--</p>
              <icon-edit class="highlight cursor" style="margin-left: 5px" @click="openEditProductParets(rowIndex)" />
            </div>
            <!-- 备注 -->
            <div v-else-if="item.dataIndex == 'remark'">
              <a-textarea placeholder="生产注意事项" size="mini" style="height: 60px" v-model="record.remark" />
            </div>
            <!-- 移除 -->
            <a-popconfirm v-else-if="item.dataIndex == 'handle'" content="确认移除？" @ok="purchaseOrders.splice(rowIndex, 1)" type="warning">
              <a-button type="text" size="mini">移除</a-button>
            </a-popconfirm>
            <p v-else>{{ record[item.dataIndex] }}</p>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>
  <!-- 生产工序模板 -->
  <SetProductionProcedure v-if="showProductionProcedure" :list="productionProcedure" :isShow="showProductionProcedure" @closed="showProductionProcedure = false" @success="getProductionProcedure" />
  <!-- 配件 -->
  <EditProductParets v-if="showEditProductParets" :currentData="purchaseOrders[currentIndex]" :isShow="showEditProductParets" @closed="showEditProductParets = false" @success="changeParets" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { createProductionPlan, findProductionProcedurePage } from '@/api/purchaseApplication'
  import { parseJson, getStrVal } from '@/utils'
  import useBaseDataStore from '@/store/modules/base-data'
  import { cloneDeep } from 'lodash-es'
  import PurchasePropPopover from './purchasePropPopover.vue'
  import SetProductionProcedure from './setProductionProcedure.vue'
  import EditProductParets from './editProductParets.vue'
  onMounted(() => {
    useBaseData.getWareHouseList()
    setDefaultData()
    getProductionProcedure()
  })
  const useBaseData = useBaseDataStore()
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: () => [],
    },
  })
  const tableColumns: Array<any> = [
    {
      title: '采购单号',
      dataIndex: 'purchaseNo',
      width: 120,
    },
    {
      title: '产品',
      dataIndex: 'sku',
      width: 160,
    },
    {
      title: '生产参数',
      dataIndex: 'prop',
      tip: '这里的生产参数直接取采购明细上的“采购参数”信息',
      width: 120,
    },
    {
      title: '材质',
      dataIndex: 'material',
      tip: '取“采购参数”上材质属性值，如果没有材质属性则为空',
      width: 60,
    },
    {
      title: '类型',
      dataIndex: 'productType',
      width: 50,
    },
    {
      title: '客户',
      dataIndex: 'companyName',
      tip: '这里的客户是指采购明细上的“采购方',
      width: 100,
    },
    {
      title: '采购数量',
      dataIndex: 'purchaseAmt',
      width: 60,
    },
    {
      title: '需生产数量',
      dataIndex: 'num',
      width: 90,
    },
    {
      title: '生产工序',
      dataIndex: 'productionProcedureId',
      width: 140,
    },
    {
      title: '配件',
      dataIndex: 'partsList',
      tip: '入有配件需要点击编辑图标单个添加',
      width: 140,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 140,
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 60,
      fixed: 'right',
    },
  ]

  const showEditDialog = ref(props.isShow)
  const purchaseOrders = ref<Array<any>>([])
  const submitLoading = ref(false)
  const warehouseInfo = ref<any>()
  const productionProcedure = ref<Array<any>>([])
  const showProductionProcedure = ref(false)
  const showEditProductParets = ref(false)
  const currentIndex = ref<number>(0)
  const productTypeMap = {
    1: '普货',
    2: '打样',
    3: '定制',
  }

  // 获取生产工序模板列表
  async function getProductionProcedure() {
    const res: any = await findProductionProcedurePage({
      pageSize: 100,
      pageNum: 1,
    })
    productionProcedure.value = res?.data?.records || []
  }
  // 初始化数据
  function setDefaultData() {
    purchaseOrders.value = cloneDeep(props.list)
    purchaseOrders.value.forEach((item: any) => {
      let purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
      item.purchaseSpecsArr = Object.values(purchaseSpecs)
    })
  }
  // 获取材质
  function getMaterial(row: any) {
    let propArr = row.purchaseSpecsArr || []
    return propArr.find((el: any) => el.name == '材质')?.purchaseValue
  }
  //设置全局
  async function setGlobal(item: any, key: string, rowIndex: number) {
    purchaseOrders.value.forEach((el: any, index: number) => {
      if (index >= rowIndex) {
        console.log(index)
        el[key] = item[key]
      }
    })
  }

  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  function openEditProductParets(index: number) {
    currentIndex.value = index
    showEditProductParets.value = true
  }
  // 保存
  async function submitData() {
    if (!warehouseInfo.value?.id) {
      Message.error('请选择生产入库仓')
      return false
    }
    let _param: any = {
      warehouseCode: warehouseInfo.value.warehouseCode,
      warehouseName: warehouseInfo.value.warehouseName,
    }
    let flag = false
    _param.productionPlans = purchaseOrders.value.map((el: any) => {
      if (!el.num) {
        flag = true
      }
      let obj = cloneDeep(el)
      obj.businessItemId = obj.id
      obj.productionAmt = obj.num
      obj.businessId = obj.billId
      obj.businessNo = obj.purchaseNo
      obj.businessNo = obj.purchaseNo
      let _purchaseSpecsArr = obj.purchaseSpecsArr?.map((prop: any) => `${prop.name}：${prop.purchaseValue}`)
      obj.purchaseSpecs = _purchaseSpecsArr?.join('\n')

      delete obj.id
      delete obj.billId
      delete obj.purchaseNo
      delete obj.num
      delete obj.purchaseSpecsArr
      return obj
    })
    if (flag) {
      Message.error('请输入需生产数量')
      return false
    }
    let res: any = await createProductionPlan(_param)
    if (!res) return false
    Message.success('创建成功')
    emit('success')
    closedDialog()
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 编辑配件
  function changeParets(row: any) {
    let { partsList, remark } = row
    purchaseOrders.value[currentIndex.value].partsList = partsList
    purchaseOrders.value[currentIndex.value].remark = remark
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    .arco-select-view-single {
      padding: 0 5px;
    }
    .arco-input-wrapper {
      padding: 0 5px;
    }
    .arco-select-view-value {
      font-size: 12px !important;
      min-height: 26px;
    }

    .arco-input,
    .arco-textarea {
      min-height: 26px;
      font-size: 12px !important;
    }
  }

  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
  .add-procedure {
    font-size: 16px;
    margin-left: 5px;
  }
</style>
